package cn.iocoder.yudao.module.system.controller.admin.tenantfile;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.system.controller.admin.tenantfile.vo.TenantFilePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenantfile.vo.TenantFileRespVO;
import cn.iocoder.yudao.module.system.controller.admin.tenantfile.vo.TenantFileSaveReqVO;
import cn.iocoder.yudao.module.system.convert.tenant.TenantFileConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenantfile.TenantFileDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import cn.iocoder.yudao.module.system.service.tenantfile.TenantFileService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 租户附件")
@RestController
@RequestMapping("/system/tenant-file")
@Validated
public class TenantFileController {

    @Resource
    private TenantFileService tenantFileService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private TenantService tenantService;

    @PostMapping("/create")
    @Operation(summary = "创建租户附件")
    @PreAuthorize("@ss.hasPermission('system:tenant-file:create')")
    public CommonResult<Long> createTenantFile(@Valid @RequestBody TenantFileSaveReqVO createReqVO) {
        if (Objects.isNull(createReqVO.getTenantId())) {
            createReqVO.setTenantId(TenantContextHolder.getTenantId());
        }
        return success(tenantFileService.createTenantFile(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新租户附件")
    @PreAuthorize("@ss.hasPermission('system:tenant-file:update')")
    public CommonResult<Boolean> updateTenantFile(@Valid @RequestBody TenantFileSaveReqVO updateReqVO) {
        tenantFileService.updateTenantFile(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除租户附件")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:tenant-file:delete')")
    public CommonResult<Boolean> deleteTenantFile(@RequestParam("id") Long id) {
        tenantFileService.deleteTenantFile(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得租户附件")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:tenant-file:query')")
    public CommonResult<TenantFileRespVO> getTenantFile(@RequestParam("id") Long id) {
        TenantFileDO tenantFile = tenantFileService.getTenantFile(id);
        return success(BeanUtils.toBean(tenantFile, TenantFileRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得附件分页")
    public CommonResult<PageResult<TenantFileRespVO>> getTenantFilePage(@Valid TenantFilePageReqVO pageReqVO) {
        if (Objects.isNull(pageReqVO.getTenantId())) {
            pageReqVO.setTenantId(TenantContextHolder.getTenantId());
        }
        PageResult<TenantFileDO> pageResult = tenantFileService.getTenantFilePage(pageReqVO);

        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.getList().stream().map(TenantFileDO::getTenantId).collect(Collectors.toList()));

        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.getList().stream().map(TenantFileDO::getOwnerUserId).collect(Collectors.toList())));
        PageResult<TenantFileRespVO> converted = TenantFileConvert.INSTANCE.convert(pageResult, userMap, tenantMap);
        return success(converted);
    }

    @GetMapping("/page-by-admin")
    @Operation(summary = "获得附件分页")
    @TenantIgnore
    public CommonResult<PageResult<TenantFileRespVO>> getTenantFilePageByAdmin(@Valid TenantFilePageReqVO pageReqVO) {
        PageResult<TenantFileDO> pageResult = tenantFileService.getTenantFilePage(pageReqVO);
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.getList().stream().map(TenantFileDO::getTenantId).collect(Collectors.toList()));
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.getList().stream().map(TenantFileDO::getOwnerUserId).collect(Collectors.toList())));
        PageResult<TenantFileRespVO> converted = TenantFileConvert.INSTANCE.convert(pageResult, userMap, tenantMap);
        return success(converted);
    }

    @GetMapping("/page-by-proxy")
    @Operation(summary = "获得附件分页")
    public CommonResult<PageResult<TenantFileRespVO>> getTenantFilePageByProxy(@Valid TenantFilePageReqVO pageReqVO) {
        if (Objects.isNull(pageReqVO.getTenantId())) {
            throw exception(new ErrorCode(100500, "必须指定客户查询"));
        }
        tenantService.validateTenantIsProxy(pageReqVO.getTenantId(), TenantContextHolder.getTenantId());
        PageResult<TenantFileDO> pageResult = TenantUtils.execute(pageReqVO.getTenantId(), () -> tenantFileService.getTenantFilePage(pageReqVO));
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.getList().stream().map(TenantFileDO::getTenantId).collect(Collectors.toList()));
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.getList().stream().map(TenantFileDO::getOwnerUserId).collect(Collectors.toList())));
        PageResult<TenantFileRespVO> converted = TenantFileConvert.INSTANCE.convert(pageResult, userMap, tenantMap);
        return success(converted);
    }


    @GetMapping("/simple-list")
    @Operation(summary = "获得附件列表")
    @Parameter(name = "tenantId", description = "编号列表", required = true)
    public CommonResult<List<TenantFileRespVO>> getTenantFileList(@RequestParam(value = "tenantId", required = false) Long tenantId) {
        if (Objects.isNull(tenantId)) {
            tenantId = TenantContextHolder.getTenantId();
        }
        List<TenantFileDO> pageResult = tenantFileService.getTenantFileList(tenantId);
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(pageResult.stream().map(TenantFileDO::getOwnerUserId).collect(Collectors.toList())));
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(pageResult.stream().map(TenantFileDO::getTenantId).collect(Collectors.toList()));
        List<TenantFileRespVO> result = pageResult.stream().map(item -> TenantFileConvert.INSTANCE.convert0(item, userMap,tenantMap)).collect(Collectors.toList());
        return success(BeanUtils.toBean(result, TenantFileRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出附件")
    @OperateLog(type = EXPORT)
    public void exportTenantFileExcel(@Valid TenantFilePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        if (Objects.isNull(pageReqVO.getTenantId())) {
            pageReqVO.setTenantId(TenantContextHolder.getTenantId());
        }
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TenantFileDO> list = tenantFileService.getTenantFilePage(pageReqVO).getList();
        // 导出 Excel
        Map<Long, AdminUserDO> userMap = TenantUtils.execute(1L, () -> adminUserService.getUserMap(list.stream().map(TenantFileDO::getOwnerUserId).collect(Collectors.toList())));
        Map<Long, TenantDO> tenantMap = tenantService.getTenantMap(list.stream().map(TenantFileDO::getTenantId).collect(Collectors.toList()));

        List<TenantFileRespVO> result = list.stream().map(item -> TenantFileConvert.INSTANCE.convert0(item, userMap,tenantMap)).collect(Collectors.toList());
        ExcelUtils.write(response, "租户附件.xls", "数据", TenantFileRespVO.class,
                result);
    }

}